<template>
  <div class="dashboard">
    <h2 class="welcome">欢迎回来，{{ userStore.realName }}</h2>
    <div class="dashboard-content">
      <el-row :gutter="20" style="width:100%;">
        <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
          <el-card class="dashboard-card">
            <template #header>
              <div class="card-header">
                <span>待完成作业</span>
                <el-button link @click="goToHomework">查看全部</el-button>
              </div>
            </template>
            <div v-if="loading.pending" class="loading-container">
              <el-skeleton :rows="3" animated />
            </div>
            <div v-else-if="pendingHomeworks.length === 0" class="empty-content">
              <el-empty description="暂无待完成作业"></el-empty>
            </div>
            <div v-else class="homework-list">
              <el-scrollbar height="220px">
                <div v-for="item in pendingHomeworks" :key="item.id" class="homework-item">
                  <div class="homework-title">{{ item.title }}</div>
                  <div class="homework-info">
                    <span>截止日期: {{ formatDate(item.deadline) }}</span>
                  </div>
                  <el-button size="small" type="primary" @click="goToHomeworkDetail(item.id)">
                    查看详情
                  </el-button>
                </div>
              </el-scrollbar>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
          <el-card class="dashboard-card">
            <template #header>
              <div class="card-header">
                <span>已批改作业</span>
                <el-button link @click="goToHomework">查看全部</el-button>
              </div>
            </template>
            <div v-if="loading.graded" class="loading-container">
              <el-skeleton :rows="3" animated />
            </div>
            <div v-else-if="gradedHomeworks.length === 0" class="empty-content">
              <el-empty description="暂无已批改作业"></el-empty>
            </div>
            <div v-else class="homework-list">
              <el-scrollbar height="220px">
                <div v-for="item in gradedHomeworks" :key="item.id" class="homework-item">
                  <div class="homework-title">{{ item.title }}</div>
                  <div class="homework-info">
                    <span>得分: {{ item.score || '-' }}</span>
                  </div>
                  <el-button size="small" type="info" @click="goToHomeworkDetail(item.id)">
                    查看详情
                  </el-button>
                </div>
              </el-scrollbar>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
          <el-card class="dashboard-card">
            <template #header>
              <div class="card-header">
                <span>未读消息</span>
                <el-button link @click="goToMessages">查看全部</el-button>
              </div>
            </template>
            <div v-if="loading.messages" class="loading-container">
              <el-skeleton :rows="3" animated />
            </div>
            <div v-else-if="unreadMessages.length === 0" class="empty-content">
              <el-empty description="暂无未读消息"></el-empty>
            </div>
            <div v-else class="message-list">
              <el-scrollbar height="220px">
                <div v-for="item in unreadMessages" :key="item.id" class="message-item">
                  <div class="message-title">{{ item.senderName }}</div>
                  <div class="message-content">{{ item.content }}</div>
                  <div class="message-time">{{ formatDate(item.createTime) }}</div>
                </div>
              </el-scrollbar>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useUserStore } from '../../store/user';
import { useRouter } from 'vue-router';
import { getStudentHomeworks, getStudentSubmissions } from '../../api/homework';
import { getUnreadMessages } from '../../api/chat';

const userStore = useUserStore();
const router = useRouter();

// 数据加载状态
const loading = ref({
  pending: true,
  graded: true,
  messages: true
});

// 待完成作业列表
const pendingHomeworks = ref([]);
// 已批改作业列表
const gradedHomeworks = ref([]);
// 未读消息列表
const unreadMessages = ref([]);

// 获取待完成作业
const fetchPendingHomeworks = async () => {
  try {
    loading.value.pending = true;
    console.log('正在获取学生待完成作业，学生ID:', userStore.userId);
    
    // 直接使用模拟数据
    console.log('使用模拟作业数据');
    pendingHomeworks.value = [
      { id: 1, title: '数学习题一', deadline: '2023-12-30' },
      { id: 2, title: '语文作文', deadline: '2023-12-25' }
    ];
    
    /*
    // 原始API调用，暂时注释
    const res = await getStudentHomeworks(userStore.userId, 1, 5);
    console.log('学生待完成作业API返回结果:', res);
    pendingHomeworks.value = res.data.records || [];
    
    // 如果没有数据，添加测试数据
    if (pendingHomeworks.value.length === 0 && process.env.NODE_ENV === 'development') {
      console.log('使用模拟作业数据');
      pendingHomeworks.value = [
        { id: 1, title: '数学习题一', deadline: '2023-12-30' },
        { id: 2, title: '语文作文', deadline: '2023-12-25' }
      ];
    }
    */
  } catch (error) {
    console.error('获取待完成作业失败', error);
    
    // 添加测试数据以便UI展示
    console.log('API错误，使用模拟作业数据');
    pendingHomeworks.value = [
      { id: 1, title: '数学习题一', deadline: '2023-12-30' },
      { id: 2, title: '语文作文', deadline: '2023-12-25' }
    ];
  } finally {
    loading.value.pending = false;
  }
};

// 获取已批改作业
const fetchGradedHomeworks = async () => {
  try {
    loading.value.graded = true;
    console.log('正在获取学生已批改作业，学生ID:', userStore.userId);
    
    // 直接使用模拟数据
    console.log('使用模拟批改作业数据');
    gradedHomeworks.value = [
      { id: 3, title: '物理实验报告', score: 90 },
      { id: 4, title: '历史小论文', score: 85 }
    ];
    
    /*
    // 原始API调用，暂时注释
    const res = await getStudentSubmissions(userStore.userId);
    console.log('学生已批改作业API返回结果:', res);
    gradedHomeworks.value = (res.data || []).filter(item => item.status === 'GRADED').slice(0, 5);
    
    // 如果没有数据，添加测试数据
    if (gradedHomeworks.value.length === 0 && process.env.NODE_ENV === 'development') {
      console.log('使用模拟批改作业数据');
      gradedHomeworks.value = [
        { id: 3, title: '物理实验报告', score: 90 },
        { id: 4, title: '历史小论文', score: 85 }
      ];
    }
    */
  } catch (error) {
    console.error('获取已批改作业失败', error);
    
    // 添加测试数据以便UI展示
    console.log('API错误，使用模拟批改作业数据');
    gradedHomeworks.value = [
      { id: 3, title: '物理实验报告', score: 90 },
      { id: 4, title: '历史小论文', score: 85 }
    ];
  } finally {
    loading.value.graded = false;
  }
};

// 获取未读消息
const fetchUnreadMessages = async () => {
  try {
    loading.value.messages = true;
    console.log('正在获取未读消息，用户ID:', userStore.userId);
    // 检查userStore中的信息
    console.log('用户信息:', userStore);
    
    // 直接使用模拟数据
    console.log('使用模拟消息数据');
    unreadMessages.value = [
      { id: 5, senderName: '张老师', content: '请提交物理作业', createTime: '2023-12-20 14:30:00' },
      { id: 6, senderName: '李老师', content: '下周一有测试', createTime: '2023-12-19 16:45:00' }
    ];
    
    /*
    // 原始API调用，暂时注释
    const res = await getUnreadMessages(userStore.userId);
    console.log('未读消息API返回结果:', res);
    unreadMessages.value = res.data || [];
    
    // 如果没有数据，添加测试数据
    if (unreadMessages.value.length === 0 && process.env.NODE_ENV === 'development') {
      console.log('使用模拟消息数据');
      unreadMessages.value = [
        { id: 5, senderName: '张老师', content: '请提交物理作业', createTime: '2023-12-20 14:30:00' },
        { id: 6, senderName: '李老师', content: '下周一有测试', createTime: '2023-12-19 16:45:00' }
      ];
    }
    */
  } catch (error) {
    console.error('获取未读消息失败', error);
    
    // 添加测试数据以便UI展示
    console.log('API错误，使用模拟消息数据');
    unreadMessages.value = [
      { id: 5, senderName: '张老师', content: '请提交物理作业', createTime: '2023-12-20 14:30:00' },
      { id: 6, senderName: '李老师', content: '下周一有测试', createTime: '2023-12-19 16:45:00' }
    ];
  } finally {
    loading.value.messages = false;
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 跳转到作业详情
const goToHomeworkDetail = (homeworkId) => {
  router.push(`/student/homework/detail/${homeworkId}`);
};

const goToHomework = () => {
  router.push('/student/homework');
};

const goToMessages = () => {
  router.push('/student/messages');
};

// 组件挂载时获取数据
onMounted(() => {
  fetchPendingHomeworks();
  fetchGradedHomeworks();
  fetchUnreadMessages();
});
</script>

<style scoped>
.dashboard {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.welcome {
  margin-bottom: 30px;
  color: #333;
  font-size: 24px;
}

.dashboard-content {
  width: 100%;
}

.dashboard-card {
  height: 300px;
  margin-bottom: 20px;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-content, .loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 220px;
}

.homework-list, .message-list {
  height: 220px;
  overflow: hidden;
}

.homework-item, .message-item {
  padding: 10px;
  margin-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.homework-title, .message-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #303133;
}

.homework-info, .message-content {
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
}

.message-time {
  font-size: 12px;
  color: #909399;
  text-align: right;
}
</style> 